new Vue({
    el: '#app',
    data() {
        return {
            fileList: [],
            tableData: [],
            form: {
                page: 1,
                limit: 15,
            },
            loading: false,
            success: 0,
            error: 0,
        }
    },
    mixins: [importMixin],
    methods: {
        submitUpload(i = 0) {
            const that = this;
            if (i < this.tableData.length) {
                if (i == 0) {//首次初始化
                    this.success = 0;
                    this.error = 0;
                }
                this.loading = true;
                if (this.tableData[i].isError) {
                    this.tableData[i].isStatus = '2';
                    this.error++;
                    this.submitUpload(i + 1);
                } else if (!this.tableData[i].Supplier_Article_SerialNumber) {
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = '供应商品内码不能为空'
                    this.error++;
                    this.submitUpload(i + 1);
                } else if (this.tableData[i].Activity_Unit_Price == 0) {
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = '活动单价不能为零'
                    this.error++;
                    this.submitUpload(i + 1);
                } else { //校验通过
                    //查询活动是否存在
                    $.ajax({
                        headers: requestHeaders(),
                        type: 'POST',
                        url: `${BASE_URL2}/generalBusiness/generalQueryByTableNameWithOriginal`,
                        data: {
                            Data: "business_activity",
                            Condition: "Row_Status<>'1' and Activity_SerialNumber='" + that.tableData[i].Activity_SerialNumber + "'"
                        },
                        success: function (business_activity) {
                            if (business_activity.length == 1) {//查询该商品是否存在
                                $.ajax({
                                    headers: requestHeaders(),
                                    type: 'POST',
                                    url: `${BASE_URL2}/generalBusiness/generalQueryByTableNameWithOriginal`,
                                    data: {
                                        Data: "business_activity_article",
                                        Condition: "Supplier_Article_SerialNumber='" + that.tableData[i].Supplier_Article_SerialNumber
                                            + "' and Activity_SerialNumber='" + that.tableData[i].Activity_SerialNumber + "'"
                                    },
                                    success: function (business_activity_article) {
                                        let data = {};
                                        if (business_activity_article.length == 1) {//修改
                                            business_activity_article[0].Activity_Unit_Price = that.tableData[i].Activity_Unit_Price
                                            business_activity_article[0].Row_Status = '0'; 
                                            data = { Modify: { business_activity_article } }
                                        } else {//添加
                                            data = { Add: { business_activity_article: [that.tableData[i]] } };
                                        }
                                        that.submitForm({ Data: JSON.stringify(data) }, (res) => {
                                            if (res.Status == 'success') {
                                                that.tableData[i].isStatus = '1';
                                                that.tableData[i].Cause = '',
                                                that.success++;
                                            } else {
                                                that.tableData[i].isStatus = '2';
                                                that.tableData[i].Cause = '未知错误(可能原因:商品名称过长)'
                                                that.error++;
                                            }
                                            that.submitUpload(i + 1);
                                        })
                                    },
                                    complete: function (XMLHttpRequest) {
                                        requestPretreatment(XMLHttpRequest);
                                    },
                                    dataType: "json"
                                });
                            } else {
                                that.tableData[i].isStatus = '2';
                                that.tableData[i].Cause = '未查询到该活动'
                                that.error++;
                                that.submitUpload(i + 1);
                            }
                        },
                        complete: function (XMLHttpRequest) {
                            requestPretreatment(XMLHttpRequest);
                        },
                        dataType: "json"
                    });
                }
            } else if (i != 0) {
                $.ajax({
                    headers: requestHeaders(),
                    url: `${BASE_URL2}/article/generateDailyArticlePurchasePrice`,
                    type: 'GET',
                    complete: function (XMLHttpRequest) {
                        if (XMLHttpRequest.status == 200) {
                            that.loading = false;
                            that.$message.success("批量导入结束")
                        }
                    },
                })
            } else {
                this.$message({
                    message: '请先导入模板后再上传',
                    type: 'warning'
                })
            }
        },
        submitForm(data, callback) {
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalSave`,
                type: 'POST',
                data,
                success: function (res) {
                    callback(res)
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
        },
        handleChange({ raw }) {//导入监听文件
            const that = this;
            var reader = new FileReader();
            reader.readAsBinaryString(raw);
            reader.onload = function (e) {
                var data = e.target.result;
                var wb = XLSX.read(data, {
                    type: 'binary' //以二进制的方式读取
                });
                var sheet = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
                var json = XLSX.utils.sheet_to_json(sheet);//利用接口实现转换。
                let Supplier_Article = [];
                let sql1 = "";
                json.forEach((item, index) => {
                    let Article_Specifications_SerialNumber = item['规格内码'] ? item['规格内码'] : ''
                    let Supplier_SerialNumber = item['供应商内码'] ? item['供应商内码'] : ''
                    if (!Supplier_Article.some(i => i[0] == Article_Specifications_SerialNumber && i[1] == Supplier_SerialNumber)) {
                        Supplier_Article.push([Article_Specifications_SerialNumber, Supplier_SerialNumber]);
                        if (index == 0) {
                            sql1 = sql1 + "business_supplier_article.Article_Specifications_SerialNumber='" + Article_Specifications_SerialNumber + "'\r\n"
                                + "and business_supplier_article.Supplier_SerialNumber='" + Supplier_SerialNumber + "'\r\n"
                        } else {
                            sql1 = sql1 + " or business_supplier_article.Article_Specifications_SerialNumber='" + Article_Specifications_SerialNumber + "'\r\n"
                                + "and business_supplier_article.Supplier_SerialNumber='" + Supplier_SerialNumber + "'\r\n"
                        }
                    }
                })
                //查询商品信息
                $.ajax({
                    headers: requestHeaders(),
                    type: 'POST',
                    url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                    data: {
                        SQLSerialNumber: 'A_business_supplier_article',
                        Condition: '',
                        ExtensionCondition: window.btoa(unescape(encodeURIComponent(`and (${sql1})`))),
                    },
                    success: function (Result) {
                        let arr = [];
                        json.forEach(item => {
                            let Activity_SerialNumber = item['活动内码'] ? item['活动内码'] : ''
                            let Article_Specifications_SerialNumber = item['规格内码'] ? item['规格内码'] : ''
                            let Supplier_SerialNumber = item['供应商内码'] ? item['供应商内码'] : ''
                            let Activity_Unit_Price = item['活动单价'] ? item['活动单价'] : 0
                            if (Result.some(i => i.Supplier_Article_SerialNumber == Supplier_SerialNumber + '-' + Article_Specifications_SerialNumber)) {
                                arr.push({
                                    ...Result.filter(i => i.Supplier_Article_SerialNumber == Supplier_SerialNumber + '-' + Article_Specifications_SerialNumber)[0],
                                    Activity_Article_SerialNumber: '',
                                    Activity_SerialNumber,
                                    Supplier_Article_SerialNumber: Supplier_SerialNumber + '-' + Article_Specifications_SerialNumber,
                                    Article_Specifications_SerialNumber,
                                    Activity_Unit_Price,
                                    isEdit: false,
                                    isStatus: '0',
                                    Cause: '',
                                })
                            } else {
                                arr.push({
                                    Activity_Article_SerialNumber: '',
                                    Activity_SerialNumber,
                                    Supplier_Article_SerialNumber: Supplier_SerialNumber + '-' + Article_Specifications_SerialNumber,
                                    Article_Specifications_SerialNumber,
                                    Activity_Unit_Price,
                                    isEdit: false,
                                    isError: true,
                                    isStatus: '2',
                                    Cause: '该商品未查到,可能原因:\r\n1.该供应商品内码不正确,2.该商品没有采购价格单',
                                })
                            }
                        });
                        that.tableData = arr
                    },
                    complete: function (XMLHttpRequest) {
                        requestPretreatment(XMLHttpRequest);
                    },
                    dataType: "json"
                })
            }
        },
        handleSizeChange(val) {
            this.form.page = 1;
            this.form.limit = val;
        },
        handleCurrentChange(val) {
            this.form.page = val;
        },
        handleEdit(row) {//修改当前行
            row.isEdit = !row.isEdit
        },
        handleRemove(index) {//移除当前行id
            this.tableData = this.tableData.filter((i, id) => id != (this.form.page - 1) * this.form.limit + index)
        },
        handleClean() {//清空
            this.$confirm('是否要清空导入数据?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.tableData = []
            }).catch(() => { });
        },
    },
})